package com.github.cdisk.xtrans.ui;

import java.io.File;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.github.cdisk.xtrans.core.BaseComponent;
import com.github.cdisk.xtrans.core.BaseComponentUI;
import com.github.cdisk.xtrans.core.ConfigFile;
import com.github.cdisk.xtrans.ui.properties.PropertiesFile;

public class Operation {

	/** 所有元件 */
	public static ConfigFile CONFIG = new ConfigFile();

	/**
	 * 直接保存，保存到原文件位置
	 * @param shell
	 */
	public static void save(Shell shell) {
		String file = CONFIG.file;
		if (file == null) {
			saveAs(shell);
		} else {
			_save(file, shell);
		}
	}

	/**
	 * 另存为
	 * @param shell
	 */
	public static void saveAs(Shell shell) {
		FileDialog filedlg = new FileDialog(shell, SWT.SAVE);
		filedlg.setText("文件另存为");
		filedlg.setFilterExtensions(new String[] {"*.xdt"});
		String file = filedlg.open();
		if (file == null)
			return;

		if (new File(file).exists()) {
			MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO);
			mb.setText("Tips");
			mb.setMessage(file + " 已经存在，是否要替换它?");
			if (mb.open() != SWT.YES) {
				return;
			}
		}
		_save(file, shell);
	}

	public static void open(Shell shell, CanvasPanel canvas) {
		FileDialog filedlg = new FileDialog(shell, SWT.OPEN);
		filedlg.setFilterExtensions(new String[] { "*.xdt" });
		filedlg.setText("打开");
		String file = filedlg.open();
		if (file == null)
			return;
		loadFile(file, shell, canvas);
	}

	public static void loadFile(String file, Shell shell, CanvasPanel canvas) {
		if (file != null) {
			try {
				shell.setText("转换编辑器 - " + file);
				CONFIG = ConfigFile.Read(file, null, false);
				/* 初始化元件时，同步将UI对象植入。 */
				for (BaseComponent component : CONFIG.components) {
					BaseComponentUI ui = component.getUi();
					if (ui == null) {
						component.setUi(new ComponentUI());
					} else if (!(ui instanceof ComponentUI)) {
						component.setUi(new ComponentUI(ui));
					}
				}
				PropertiesFile.put("lastOpenFile", file); // 保存最后打开文件到本地临时配置记录中
			} catch (Exception excep) {
				excep.printStackTrace();
				shell.setText("转换编辑器 - 打开失败 - " + file);
				MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
				mb.setText("打开文件失败");
				mb.setMessage(excep.toString());
				mb.open();
			}
		} else {
			shell.setText("转换编辑器 - 新文件");
			CONFIG = new ConfigFile();
		}
		canvas.redraw();
	}

	private static void _save(String file, Shell shell) {
		try {
			CONFIG.file = file;
			CONFIG.save();
			shell.setText("转换编辑器 - " + file + " - (保存成功)");
			PropertiesFile.put("lastOpenFile", file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
